﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using XQ.SP.BllServices;
using XQ.SP.Model;
using XM.Comm;
using XM.PermissionFilter;
using System.Data;
using System.Data.OleDb;
using System.Web.Script.Serialization;

namespace XiaoQu.Controllers
{
    /// <summary>
    /// 用户数据权限
    /// </summary>
    [Description("用户数据权限")]
    public class UserInfoController : Controller
    {
        XQ.SP.BllServices.UserInfoBLL bllBase = new XQ.SP.BllServices.UserInfoBLL();

        #region 后台管理
        #region 列表
        [Description("列表")]
        [PermissionFilter]
        public ActionResult List(int pageIndex = 1)
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "username", Text = "用户 名" });
            ListSeach.Add(new SelectListItem { Value = "pwd", Text = "密码" });
            ListSeach.Add(new SelectListItem { Value = "city", Text = "县市" });
            ListSeach.Add(new SelectListItem { Value = "towns", Text = "乡镇" });
            ListSeach.Add(new SelectListItem { Value = "village", Text = "村名称" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfo ";
            modelP.fldName = " * ";
            modelP.pageSize = 20;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }

            // 根据登录用户导出数据
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            //if (Session["Admin"] != null && Session["Admin"].ToString() == "0")
            //{
            var user = (UserInfoItem)Session["Users"];
            if (!string.IsNullOrWhiteSpace(user.UserName))
            {
                modelP.strCondition += " and UserName like '" + user.UserName + "%' ";
            }
            //}

            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoItem> list = bllBase.DataTableToList(modelP.dt);
            return View(new PagedList<XQ.SP.Model.UserInfoItem>(list, pageIndex, pageSize, modelP.counts));
        }
        #endregion

        #region 编辑
        [Description("编辑")]
        [PermissionFilter]
        public ActionResult Edit(long id = 0, int tid = 0)
        { 
            // 根据登录用户
            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            var user = (UserInfoItem)Session["Users"];
            if (user.UserName != "5134")
            {
                return View("NoEdit");
            }

            UserInfoItem item = new UserInfoItem();
            item.Status = tid;
            if (id != 0)
            {
                item = bllBase.GetModel(id);
            }

            return View(item);
        }

        [Description("编辑")]
        [PermissionFilter]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(UserInfoItem model)
        {




            #region
            try
            {
                string s = "";
                if (model.UserName.Length > 80)
                    s = "用户 名字符数不能多于80 !";
                if (model.Pwd.Length > 80)
                    s = "密码字符数不能多于80 !";
                if (model.City.Length > 80)
                    s = "县市字符数不能多于80 !";
                if (model.Towns.Length > 80)
                    s = "乡镇字符数不能多于80 !";
                if (model.Village.Length > 80)
                    s = "村名称字符数不能多于80 !";
                if (!string.IsNullOrEmpty(s))
                {
                    ModelState.AddModelError("", s);
                    return View(model);
                }
            }
            catch { }
            #endregion

            #region
            #endregion
            if (model.Id > 0)
            {
                var userCurr = UsersInfo.GetUserH();
                model.Modified = DateTime.Now;
                model.Modifier = userCurr.Id;
                if (bllBase.Update(model))
                    return RedirectToAction("List");
                else
                {
                    ModelState.AddModelError("", "编辑失败");
                }
            }
            else
            {
                var userCurr = UsersInfo.GetUserH();
                model.Creator = userCurr.Id;
                model.Created = DateTime.Now;
                model.Modified = DateTime.Now;
                if (bllBase.Add(model) > 0)
                    return RedirectToAction("List");
                else
                {
                    ModelState.AddModelError("", "添加失败");
                }
            }
            return View(model);
        }
        #endregion

        #region 删除
        [Description("删除")]
        [PermissionFilter]
        public JsonResult Deletes(string ids, long uid)
        {
            if (bllBase.DeleteList(ids))
                return Json("true", JsonRequestBehavior.AllowGet);

            return Json("false", JsonRequestBehavior.AllowGet);
        }
        #endregion



        #region 修改密码
        [Description("修改密码")]
        [PermissionFilter]
        public ActionResult Pwd()
        {
            UserInfoItem item = new UserInfoItem();

            if (Session["Users"] == null)
            {
                return RedirectToAction("LoginUIA", "User");
            }
            else
            {
                var user = (UserInfoItem)Session["Users"];
                item = bllBase.GetModel(user.Id);
            }

            return View(item);
        }

        [Description("修改密码")]
        [PermissionFilter]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Pwd(UserInfoItem model)
        {
            var result = new { status = true, msg = "修改密码成功" };
            #region
            try
            {
                string s = "";
                if (model.UserName.Length > 80)
                    s = "用户 名字符数不能多于80 !";
                if (model.Pwd.Length > 80)
                    s = "密码字符数不能多于80 !";
                if (!string.IsNullOrEmpty(s))
                {
                    result = new { status = false, msg = s };
                    return new ContentResult
                    {
                        Content = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(new { result }),
                        ContentType = "application/json"
                    };
                }
            }
            catch { }
            #endregion

            #region
            #endregion
            if (model.Id > 0)
            {
                model.Modified = DateTime.Now;
                model.Modifier = model.Id;
                if (!bllBase.Update(model))
                {
                    result = new { status = false, msg = "操作失败" };
                }
            }
            return new ContentResult
            {
                Content = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(new { result }),
                ContentType = "application/json"
            };
        }
        #endregion


        [HttpPost]
        public ActionResult UploadUsers(HttpPostedFileBase file)
        {
            var result = new { status = true };
            try
            {
                #region
                string fileT = file.FileName;
                if (fileT.Length > 10)
                {
                    fileT = fileT.Substring(fileT.Length - 10);
                }
                fileT = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileT;
                XQ.Common.Images img = new XQ.Common.Images();
                string savePath = img.GetPath();
                string uploadPath = Server.MapPath("~" + savePath);

                file.SaveAs(uploadPath + fileT);
                DataTable dt = GetDataFromExcelByConn(uploadPath + fileT);

                XQ.SP.BllServices.UserInfoBLL bllui = new XQ.SP.BllServices.UserInfoBLL();
                int r = 0;

                // 是否管理员
                var creator = 1L;
                if (Session["Users"] != null)
                {
                    var user = (UserInfoItem)Session["Users"];
                    creator = user.Id;
                }
                foreach (DataRow dr in dt.Rows)
                {
                    if (r == 0)
                    {
                        r++;
                        continue;
                    }
                    // 根据编码查找是否已经存在
                    XQ.SP.Model.UserInfoItem itemUi = null;
                    if (itemUi == null & !string.IsNullOrEmpty(dr[0].ToString().Trim()))
                    {
                        itemUi = bllui.GetModelWhereStr(" UserName='" + dr[0].ToString().Trim() + "' ");
                    }

                    // 编码为空的忽略
                    if (dr[0].ToString().Trim() == "")
                    {
                        continue;
                    }

                    if (itemUi != null)
                    {
                        itemUi.UserName = dr[0].ToString().Trim();
                        Random rd = new Random();
                        itemUi.Pwd = rd.Next(100000, 999999).ToString();
                        if (dr[1] != null)
                            itemUi.City = dr[1].ToString().Trim();
                        if (dr[2] != null)
                            itemUi.Towns = dr[2].ToString().Trim();
                        if (dr[3] != null)
                            itemUi.Village = dr[3].ToString().Trim();
                        itemUi.Modifier = creator;
                        itemUi.Modified = DateTime.Now;

                        bllui.Update(itemUi);
                    }
                    else
                    {
                        itemUi = new UserInfoItem();
                        itemUi.UserName = dr[0].ToString().Trim();
                        Random rd = new Random();
                        itemUi.Pwd = rd.Next(100000, 999999).ToString();
                        if (dr[1] != null)
                            itemUi.City = dr[1].ToString().Trim();
                        if (dr[2] != null)
                            itemUi.Towns = dr[2].ToString().Trim();
                        if (dr[3] != null)
                            itemUi.Village = dr[3].ToString().Trim();

                        itemUi.Status = 0;
                        itemUi.Creator = creator;
                        itemUi.Created = DateTime.Now;
                        itemUi.Modifier = creator;
                        itemUi.Modified = DateTime.Now;

                        bllui.Add(itemUi);
                    }
                }
                #endregion
            }
            catch
            {
                result = new { status = false };
            }

            //return RedirectToAction("List");
            return new ContentResult
            {
                Content = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }.Serialize(new { result }),
                ContentType = "application/json"
            };
        }
        DataTable GetDataFromExcelByConn(string filePath = "")
        {
            string fileType = System.IO.Path.GetExtension(filePath);

            bool hasTitle = false;

            using (DataSet ds = new DataSet())
            {
                string strCon = string.Format("Provider=Microsoft.Jet.OLEDB.{0}.0;" +
                                "Extended Properties=\"Excel {1}.0;HDR={2};IMEX=2;\";" +
                                "data source={3};",
                                (fileType == ".xls" ? 4 : 12), (fileType == ".xls" ? 8 : 12), (hasTitle ? "Yes" : "NO"), filePath);
                string strCom = " SELECT * FROM [Sheet1$]";
                using (OleDbConnection myConn = new OleDbConnection(strCon))
                using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
                {
                    myConn.Open();
                    myCommand.Fill(ds);
                }
                if (ds == null || ds.Tables.Count <= 0) return null;
                return ds.Tables[0];
            }
        }

        #endregion

        #region 个人中心

        #region 个人中心列表
        [Description("个人中心列表")]
        [PermissionFilter]
        public ActionResult MyList(int pageIndex = 1)
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "username", Text = "用户 名" });
            ListSeach.Add(new SelectListItem { Value = "pwd", Text = "密码" });
            ListSeach.Add(new SelectListItem { Value = "city", Text = "县市" });
            ListSeach.Add(new SelectListItem { Value = "towns", Text = "乡镇" });
            ListSeach.Add(new SelectListItem { Value = "village", Text = "村名称" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfo ";
            modelP.fldName = " * ";
            modelP.pageSize = 20;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }
            modelP.strCondition += " and Creator ='" + UsersInfo.GetUsersID() + "' ";
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoItem> list = bllBase.DataTableToList(modelP.dt);
            return View(new PagedList<XQ.SP.Model.UserInfoItem>(list, pageIndex, pageSize, modelP.counts));
        }
        #endregion

        #region 个人中心编辑
        [Description("个人中心编辑")]
        [PermissionFilter]
        public ActionResult MyEdit(long id = 0, int tid = 0)
        {
            UserInfoItem item = new UserInfoItem();
            item.Status = tid;
            if (id != 0)
            {
                item = bllBase.GetModel(id);
            }




            return View(item);
        }

        [Description("个人中心编辑")]
        [PermissionFilter]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MyEdit(UserInfoItem model)
        {




            #region
            try
            {
                string s = "";
                if (model.UserName.Length > 80)
                    s = "用户 名字符数不能多于80 !";
                if (model.Pwd.Length > 80)
                    s = "密码字符数不能多于80 !";
                if (model.City.Length > 80)
                    s = "县市字符数不能多于80 !";
                if (model.Towns.Length > 80)
                    s = "乡镇字符数不能多于80 !";
                if (model.Village.Length > 80)
                    s = "村名称字符数不能多于80 !";
                if (!string.IsNullOrEmpty(s))
                {
                    ModelState.AddModelError("", s);
                    return View(model);
                }
            }
            catch { }
            #endregion

            #region
            #endregion
            if (model.Id > 0)
            {
                model.Modified = DateTime.Now;
                model.Modifier = UsersInfo.GetUser().Id;
                if (bllBase.Update(model))
                    return RedirectToAction("MyList");
                else
                {
                    ModelState.AddModelError("", "编辑失败");
                }
            }
            else
            {
                model.Creator = UsersInfo.GetUser().Id;
                model.Created = DateTime.Now;
                model.Modified = DateTime.Now;
                if (bllBase.Add(model) > 0)
                    return RedirectToAction("MyList");
                else
                {
                    ModelState.AddModelError("", "添加失败");
                }
            }
            return View(model);
        }
        #endregion

        #region 个人中心删除
        [Description("个人中心删除")]
        [PermissionFilter]
        public ActionResult MyDelete(long id, int pageIndex)
        {
            var item = bllBase.GetModel(id);

            if (bllBase.Delete(id))
                return RedirectToAction("MyList", new { pageIndex = pageIndex });
            else
                return RedirectToAction("MyList");
        }
        #endregion
        #endregion

        #region PC端页面
        #region 查询页面
        [Description("查询页面")]
        [PermissionFilter]
        public ActionResult Sele(int pageIndex = 1)
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "name", Text = "标题" });
            ListSeach.Add(new SelectListItem { Value = "keys", Text = "关键字" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfo ";
            modelP.fldName = " * ";
            modelP.pageSize = 20;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoItem> list = bllBase.DataTableToList(modelP.dt);

            return View(new PagedList<XQ.SP.Model.UserInfoItem>(list, pageIndex, pageSize, modelP.counts));
        }
        #endregion
        #region 详细
        [Description("详细页面")]
        [PermissionFilter]
        public ActionResult D(long id = 1)
        {
            var item = bllBase.GetModel(id);
            return View(item);
        }
        #endregion
        #endregion

        #region APP 小程序 对外接口
        #region 查询接口
        [Description("实体列表接口")]
        [PermissionFilter]
        public JsonResult Selei(int pageIndex = 1, Int64 Id = 0, String UserName = "", String Pwd = "", String City = "", String Towns = "", String Village = "", Int32 Status = 0, Int64 Creator = 0, String Created = "", Int64 Modifier = 0, String Modified = "")
        {
            string valueStr = Request.Form["search_input"];
            string search_type = Request.Form["search_type"];
            List<SelectListItem> ListSeach = new List<SelectListItem>();
            ListSeach.Add(new SelectListItem { Value = "name", Text = "标题" });
            ListSeach.Add(new SelectListItem { Value = "keys", Text = "关键字" });
            ViewBag.ListSeachType = ListSeach;
            @ViewBag.pageIndex = pageIndex;
            @ViewBag.ListSeachValue = valueStr;

            #region
            int pageSize = 20;
            XQ.Model.Pager.Pager modelP = new XQ.Model.Pager.Pager();
            modelP.tableName = " UserInfo ";
            modelP.fldName = " * ";
            modelP.pageSize = pageSize;
            modelP.page = pageIndex;
            modelP.fldSort = " Id ";
            modelP.sort = 1;
            modelP.id = " Id ";
            modelP.dist = 1;
            if (!string.IsNullOrEmpty(valueStr))
            {
                modelP.strCondition += " and " + search_type + " like '%" + valueStr + "%' ";
            }

            if (Id != 0)
            {
                modelP.strCondition += " and Id =" + Id + " ";
            }
            if (!string.IsNullOrEmpty(UserName))
            {
                modelP.strCondition += " and UserName like '%" + UserName + "%' ";
            }
            if (!string.IsNullOrEmpty(Pwd))
            {
                modelP.strCondition += " and Pwd like '%" + Pwd + "%' ";
            }
            if (!string.IsNullOrEmpty(City))
            {
                modelP.strCondition += " and City like '%" + City + "%' ";
            }
            if (!string.IsNullOrEmpty(Towns))
            {
                modelP.strCondition += " and Towns like '%" + Towns + "%' ";
            }
            if (!string.IsNullOrEmpty(Village))
            {
                modelP.strCondition += " and Village like '%" + Village + "%' ";
            }
            if (Status != 0)
            {
                modelP.strCondition += " and Status =" + Status + " ";
            }
            if (Creator != 0)
            {
                modelP.strCondition += " and Creator =" + Creator + " ";
            }
            if (!string.IsNullOrEmpty(Created))
            {
                modelP.strCondition += " and Created like '%" + Created + "%' ";
            }
            if (Modifier != 0)
            {
                modelP.strCondition += " and Modifier =" + Modifier + " ";
            }
            if (!string.IsNullOrEmpty(Modified))
            {
                modelP.strCondition += " and Modified like '%" + Modified + "%' ";
            }
            modelP = DBUtility.DbHelperSQL.GetPage(modelP);
            #endregion
            List<XQ.SP.Model.UserInfoItem> list = bllBase.DataTableToList(modelP.dt);

            return Json(list, JsonRequestBehavior.AllowGet);
            //return View(new PagedList<XQ.SP.Model.UserInfoItem>(list, pageNo, pageSize, pager.counts));
        }
        #endregion
        #region 单个实体接口
        [Description("单个实体接口")]
        [PermissionFilter]
        public JsonResult Di(long id = 0)
        {
            var item = bllBase.GetModel(id);
            return Json(item, JsonRequestBehavior.AllowGet);
        }
        #endregion


        #region 单个实体接口
        [Description("单个实体接口")]
        [PermissionFilter]
        public JsonResult Login(string name = "", string pwd = "")
        {
            var item = bllBase.GetModelWhereStr(" UserName='" + name + "' and Pwd='" + pwd + "' ");
            if (item != null)
            {
                return Json("true", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json("false", JsonRequestBehavior.AllowGet);
            }
            return Json(item, JsonRequestBehavior.AllowGet);
        }
        #endregion
        #endregion
    }
}

